package com.lapula.crazyface;

import java.util.ArrayList;
import java.util.List;

import jp.co.cyberagent.android.gpuimage.GPUImage;
import jp.co.cyberagent.android.gpuimage.sample.utils.CameraHelper;
import jp.co.cyberagent.android.gpuimage.sample.utils.CameraHelper.CameraInfo2;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import cn.sharesdk.framework.ShareSDK;

import com.lapula.crazyface.entity.AngryEmotion;
import com.lapula.crazyface.entity.BeileipiEmotion;
import com.lapula.crazyface.entity.BlinkEmotion;
import com.lapula.crazyface.entity.CryEmotion;
import com.lapula.crazyface.entity.Emotion;
import com.lapula.crazyface.entity.GlassEmotion;
import com.lapula.crazyface.entity.HuaixiaoEmotion;
import com.lapula.crazyface.entity.KuEmotion;
import com.lapula.crazyface.entity.MaimengEmotion;
import com.lapula.crazyface.entity.ShameEmotion;
import com.lapula.crazyface.entity.YunEmotion;
import com.lapula.crazyface.util.ActivityStack;
import com.lapula.crazyface.util.CameraUtils;
import com.lapula.crazyface.util.FaceEmotion;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends Activity implements OnClickListener {
	private Button shootBtn;

	private GLSurfaceView surfaceView;
	private GPUImage mGPUImage;
	private CameraHelper mCameraHelper;
	private CameraLoader mCamera;

	private String imageSaveDir;

	private ProgressBar progressBar;
	private int progressValue;
	private Thread progressBarUpdateThread;
	private static final int PROGRESS_BAR_STOP = 0x10000;
	private static final int PROGRESS_BAR_CONTINUE = 0x10001;
	private static final int SHOW_CANCEL_CONFIRM_VIEW = 0x10002;
	private static final int GOTO_PREVIEW_ACTIVITY = 0x10003;

	// private FaceView faceView;
	private boolean isPreview = false;

	private HorizontalListView faceListView;

	private ImageView cancelImageView;
	private ImageView confirmImageView;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.setContentView(R.layout.activity_main);
		ActivityStack.getInstance().add(this);

		surfaceView = (GLSurfaceView) findViewById(R.id.camera_view_finder);
		mGPUImage = new GPUImage(this);
		mGPUImage.setGLSurfaceView(surfaceView);

		mCameraHelper = new CameraHelper(this);
		mCamera = new CameraLoader();

		View cameraSwitchView = findViewById(R.id.img_switch_camera);
		cameraSwitchView.setOnClickListener(this);
		if (!mCameraHelper.hasFrontCamera() || !mCameraHelper.hasBackCamera()) {
			cameraSwitchView.setVisibility(View.GONE);
		}

		shootBtn = (Button) findViewById(R.id.btn_shoot);
		shootBtn.setOnTouchListener(shootTouchListener);

		faceListView = (HorizontalListView) findViewById(R.id.lv_face);
		FaceListAdapter faceListAdapter = new FaceListAdapter(this);
		List<FaceItem> faceItems = new ArrayList<FaceItem>();
		faceItems.add(new FaceItem("生气", R.drawable.angry, AngryEmotion.class)); // 0
		faceItems.add(new FaceItem("雷劈", R.drawable.beileipi, BeileipiEmotion.class)); // 1
		faceItems.add(new FaceItem("星闪", R.drawable.blink, BlinkEmotion.class)); // 2
		faceItems.add(new FaceItem("大哭", R.drawable.daku, CryEmotion.class)); // 3
		faceItems.add(new FaceItem("坏笑", R.drawable.huaixiao, HuaixiaoEmotion.class)); // 4
		faceItems.add(new FaceItem("流眼泪", R.drawable.liuyanlei, KuEmotion.class)); // 5
		faceItems.add(new FaceItem("卖萌", R.drawable.lovely, MaimengEmotion.class)); // 6
		faceItems.add(new FaceItem("害羞", R.drawable.shame, ShameEmotion.class)); // 7
		faceItems.add(new FaceItem("晕", R.drawable.dizzy, YunEmotion.class)); // 8
		faceItems.add(new FaceItem("眼镜", R.drawable.glass, GlassEmotion.class)); // 9
		faceListAdapter.addAll(faceItems);
		faceListView.setAdapter(faceListAdapter);
		faceListView.setOnItemSelectedListener(expressionSelectListener);

		progressBar = (ProgressBar) findViewById(R.id.progress_bar);
		progressBar.setProgress(0);
		progressBar.setMax(Constants.MAX_RECORD_MSEC);

		cancelImageView = (ImageView) findViewById(R.id.iv_cancel);
		cancelImageView.setVisibility(View.INVISIBLE);
		cancelImageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				resetRecord();
			}
		});

		confirmImageView = (ImageView) findViewById(R.id.iv_confirm);
		confirmImageView.setVisibility(View.INVISIBLE);
		confirmImageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				D.I().previewPics();
				toFacePreviewActivity();
			}
		});

		FaceEmotion.init(this);
		ShareSDK.initSDK(this);
		
		IWXAPI api = WXAPIFactory.createWXAPI(this, "wx310ac3cd1e526d49", false);
		api.registerApp("wx310ac3cd1e526d49");
	}

	private OnItemSelectedListener expressionSelectListener = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			FaceItem item = (FaceItem) arg0.getAdapter().getItem(arg2);
			Emotion e = item.getEmotionInstance(MainActivity.this);
			if (e != null){
				FaceEmotion.I.setEmotion(e);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	};

	private OnTouchListener shootTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent event) {
			int action = event.getAction();
			if (action == MotionEvent.ACTION_DOWN) {
				D.I().setRecording(true);
				shootBtn.setText("松开暂停");
				shootBtn.setBackgroundResource(R.drawable.shoot_btn_bg_pressed);
				progressBarUpdateThread = new ProgressBarUpdateThread();
				progressBarUpdateThread.start();
				Log.e("debug", "start record");
			} else if (action == MotionEvent.ACTION_UP) {
				D.I().setRecording(false);
				shootBtn.setText("按住拍摄");
				shootBtn.setBackgroundResource(R.drawable.shoot_btn_bg_normal);
				progressBarUpdateThread.interrupt();
			}
			return false;
		}
	};

	private class ProgressBarUpdateThread extends Thread {
		@Override
		public void run() {
			try {
				for (int i = progressBar.getProgress(); i < Constants.MAX_RECORD_MSEC; i += Constants.UPDATE_PROGRESS_BAR_MSEC_INTERVAL) {
					progressValue += Constants.UPDATE_PROGRESS_BAR_MSEC_INTERVAL;
					Thread.sleep(Constants.UPDATE_PROGRESS_BAR_MSEC_INTERVAL);
					Message msg1 = new Message();
					msg1.what = PROGRESS_BAR_CONTINUE;
					mHandler.sendMessage(msg1);
					if (progressValue > Constants.MIN_RECORD_MSEC) {
						Message msg2 = new Message();
						msg2.what = SHOW_CANCEL_CONFIRM_VIEW;
						mHandler.sendMessage(msg2);
					}
				}

				Message msg3 = new Message();
				msg3.what = GOTO_PREVIEW_ACTIVITY;
				mHandler.sendMessage(msg3);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void resetRecord() {
		imageSaveDir = null;
		progressValue = 0;
		progressBar.setProgress(0);
		cancelImageView.setVisibility(View.INVISIBLE);
		confirmImageView.setVisibility(View.INVISIBLE);
		D.I().clearRecordingPics();
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PROGRESS_BAR_STOP:
				Thread.currentThread().interrupt();
				break;

			case PROGRESS_BAR_CONTINUE:
				if (!Thread.currentThread().isInterrupted()) {
					progressBar.setProgress(progressValue);
				}
				break;

			case SHOW_CANCEL_CONFIRM_VIEW:
				cancelImageView.setVisibility(View.VISIBLE);
				confirmImageView.setVisibility(View.VISIBLE);
				break;

			case GOTO_PREVIEW_ACTIVITY:
				D.I().previewPics();
				toFacePreviewActivity();
				break;
			}
		}
	};

	@Override
	public void onResume() {
		super.onResume();
		mCamera.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		mCamera.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onClick(final View v) {
		switch (v.getId()) {
		case R.id.img_switch_camera:
			mCamera.switchCamera();
			break;
		}
	}

	private class CameraLoader {
		private int mCurrentCameraId = 0;
		private Camera mCameraInstance;

		public void onResume() {
			setUpCamera(mCurrentCameraId);
		}

		public void onPause() {
			releaseCamera();
		}

		public void switchCamera() {
			releaseCamera();
			mCurrentCameraId = (mCurrentCameraId + 1) % mCameraHelper.getNumberOfCameras();
			setUpCamera(mCurrentCameraId);
		}

		private void setUpCamera(final int id) {
			mCameraInstance = getCameraInstance(id);

			// 设置camera参数
			Parameters parameters = mCameraInstance.getParameters();
			// parameters.setPreviewFpsRange(Constants.PREVIEW_FRAME_RATE_MIN,
			// Constants.PREVIEW_FRAME_RATE_MAX);

			// 设置帧速率
			// List<int[]> supportPreviewFpsRange =
			// parameters.getSupportedPreviewFpsRange();
			parameters.setPreviewFrameRate(9);

			// 设置分辨率
			List<Size> sizes = parameters.getSupportedPreviewSizes();
			Size optimalSize = CameraUtils.getOptimalPreviewSize(sizes, Constants.PREVIEW_SIZE_WIDTH, Constants.PREVIEW_SIZE_HEIGHT);
			// optimalSize.height);
			D.I().setImageSize(optimalSize);
			parameters.setPreviewSize(optimalSize.width, optimalSize.height);

			if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
				parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
			}
			mCameraInstance.setParameters(parameters);

			int orientation = mCameraHelper.getCameraDisplayOrientation(MainActivity.this, mCurrentCameraId);
			CameraInfo2 cameraInfo = new CameraInfo2();
			mCameraHelper.getCameraInfo(mCurrentCameraId, cameraInfo);
			boolean flipHorizontal = cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT ? true : false;
			mGPUImage.setUpCamera(mCameraInstance, orientation, flipHorizontal, false);
			// Log.e("orientation", String.valueOf(orientation));
			FaceEmotion.I.setCameraOrientation(orientation);
		}

		public Camera getCamera() {
			return mCameraInstance;
		}

		/** A safe way to get an instance of the Camera object. */
		private Camera getCameraInstance(final int id) {
			Camera c = null;
			try {
				c = mCameraHelper.openCamera(id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return c;
		}

		private void releaseCamera() {
			mCameraInstance.setPreviewCallback(null);
			mCameraInstance.release();
			mCameraInstance = null;
		}
	}

	private void toFacePreviewActivity() {
		Intent intent = new Intent(this, FacePreviewActivity.class);
		intent.putExtra("imageSaveDir", imageSaveDir);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		resetRecord();
		startActivity(intent);
	}
}
